﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).
using System;
using System.Collections.Generic;
#if NET35 || NET40
using System.Linq;

#elif NET20
using System.Collections.Generic;
using System.Data.SqlClient;
using Z.Net.Legacy20;
#endif
using System.Linq;

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        /// <summary>
        ///     Sets SQL bulk merge action.
        /// </summary>
        public void SetSqlMergeActionBulk()
        { 
            IEnumerable<string> sqlSetValueSelectList = MappingList.Where(x => !Setting.PrimaryKeys.Contains(x.DestinationColumn) && x.DestinationColumn != Setting.IdentityColumn && x.DestinationColumn != TemporaryColumnName)
                .Select(x => string.Format("A.[{0}] = B.[{0}]", x.DestinationColumn));
            IEnumerable<string> sqlWhereSelectList = Setting.PrimaryKeys.Select(x => string.Format("A.[{0}]" + "=" + "B.[{0}]", x));
            IEnumerable<string> sqlInsertColumnSelectList = MappingList.Where(x => x.DestinationColumn != Setting.IdentityColumn && x.DestinationColumn != TemporaryColumnName)
                .Select(x => string.Format("[{0}]", x.DestinationColumn));

            string sqlSetValue = string.Join(", ", sqlSetValueSelectList.ToArray());
            string sqlWhere = String.Join(" AND ", sqlWhereSelectList.ToArray());
            string sqlInserColumns = string.Join(", ", sqlInsertColumnSelectList.ToArray());
 
            string sqlActionUpdate = string.Format(SqlUpdateActionBulk, SqlBulkCopy.DestinationTableName, TemporaryTableName, sqlSetValue, sqlWhere);
            string sqlActionInsert = string.Format(SqlMergeInsertActionBulk, SqlBulkCopy.DestinationTableName, TemporaryTableName, sqlWhere, sqlInserColumns, sqlInserColumns);

            SqlActionBulk1 = SqlBulkCopy.BatchSize == 0
                ? sqlActionUpdate
                : string.Format(SqlBatchOperation, TemporaryTableName, sqlActionUpdate, TemporaryColumnName, SqlBulkCopy.BatchSize);

            SqlActionBulk2 = SqlBulkCopy.BatchSize == 0
                ? sqlActionInsert
                : string.Format(SqlBatchOperationAnd, TemporaryTableName, sqlActionInsert, TemporaryColumnName, SqlBulkCopy.BatchSize);
        }
    }
}